<?php
/**
 * #Celebrate Shieh
 *             ,%%%%%%%%,
 *           ,%%/\%%%%/\%%
 *          ,%%%\c "" J/%%%
 * %.       %%%%/ o  o \%%%
 * `%%.     %%%%    _  |%%%
 *  `%%     `%%%%(__Y__)%%'
 *  //       ;%%%%`\-/%%%'
 * ((       /  `%%%%%%%'
 *  \\    .'          |
 *   \\  /       \  | |
 *    \\/         ) | |
 *     \         /_ | |__
 *     (___________))))))) 攻城湿
 *
 *        _       _
 * __   _(_)_   _(_) __ _ _ __
 * \ \ / / \ \ / / |/ _` |'_ \
 *  \ V /| |\ V /| | (_| | | | |
 *   \_/ |_| \_/ |_|\__,_|_| |_|
 */

namespace App\Services;

use App\Models\System\Permission;
use Illuminate\Http\Request;

class PermissionService
{

    use Service;

    /**
     * 权限新增
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function PermissionStoreService( $request )
    {
        $validator = $this->getAdminValidator()->PermissionStoreValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        Permission::CreateModel($request->all());
        return back()->with('success', $this->getErrorCode()::message(209));
    }

    /**
     * 权限编辑页面
     *
     * @param $id
     *
     * @return mixed
     */
    public function PermissionEditService( $id )
    {
        $select     = [ 'id', 'parent_id', 'name', 'pid', 'label', 'icon', 'sort_order' ];
        $permission = Permission::FindModel($id, $select);
        return view('system.permission.edit', compact('permission'));
    }

    /**
     * 权限修改
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function PermissionUpdateService( $request )
    {
        $validator = $this->getAdminValidator()->PermissionUpdateValidator($request);
        if ( $validator->first() ) return back()->with('error', $validator->first());
        $select     = [ 'id', 'parent_id', 'name', 'pid', 'label', 'icon', 'sort_order' ];
        $permission = Permission::FindModel($request->input('id'), $select);
        $permission->update($request->all());
        return back()->with('success', $this->getErrorCode()::message(203));
    }

    /**
     * 权限删除
     *
     * @param $id
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function PermissionDestroyService( $id )
    {
        $error = $this->getErrorCode();
        if ( ! Permission::check_children($id, [ 'id' ]) ) return back()->with('error', $error::message(1025));
        Permission::DestroyModel($id);
        return back()->with('success', $error::message(204));
    }

    /**
     * 权限排序
     *
     * @param Request $request
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function PermissionOrderService( $request )
    {
        $array = json_decode($request->input('sort'), TRUE);
        if ( ! $this->getCommon()->sort($array, 'permission', 0, 3, 1) ) return message($this->getErrorCode()::message(2196));
        return data();
    }

}
